package com.pig.service;

import com.pig.exception.UnExceptDataException;
import com.pig.pojo.ImageVo;
import com.pig.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    private static Set<String> typeSet = new HashSet<>();

    private String fileDir = "/usr/local/pqmc/goodsimages/";

    private String url = "http://159.75.44.225:8756/";

    static {
        String[] type = {".jpg", ".png", ".gif"};
        typeSet.addAll(Arrays.asList(type));
    }

    @Override
    public ImageVo upload(MultipartFile myFile, Integer categoryId) {
        //1.获取文件名字
        String fileName = myFile.getOriginalFilename();
        //获取文件后缀且全部转换为小写
        String fileType = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        //判断图片是否符合要求
        if (!typeSet.contains(fileType)) {
            throw new UnExceptDataException("上传图片的类型不符合需求！");
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(myFile.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width == 0 || height == 0) {
                throw new UnExceptDataException("你想上传木马？？");
            }
            File dirFile = new File(fileDir + categoryId);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            String fileUuidName = UUID.randomUUID().toString().replace("-", "")+fileType;
            String diskPath = dirFile +"/"+ fileUuidName;
            File realImg = new File(diskPath);
            myFile.transferTo(realImg);
            String showUrl = url + categoryId+"/"+fileUuidName;
            return ImageVo.success(showUrl, width, height);
        } catch (IOException e) {
            e.printStackTrace();
            return ImageVo.fail();
        }
    }
}

